package com.sduept.nwld.dataserver.manager.message;

import java.util.Calendar;
import java.util.Date;
import java.util.List;


import com.alibaba.fastjson.JSONArray;
import com.sduept.component.message.model.CimEquipmentUpdateMessage;
import com.sduept.core.dao.SuperDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 一次设备更新消息管理
 *
 */
@Service
public class CimEquipmentUpdateMessageManager {
	@Autowired
	private SuperDAO superDao;

	/**
	 * 查询全部消息
	 * @return
	 */
	public List<CimEquipmentUpdateMessage> findAllMessage() {
		return superDao.findAll(CimEquipmentUpdateMessage.class, "order by updateTime desc");
	}

	/**
	 * 根据条件
	 * @param updateTimeStart
	 * @param updateTimeEnd
	 * @param name
	 * @return
	 */
	public List<CimEquipmentUpdateMessage> searchByCondition(Date updateTimeStart, Date updateTimeEnd, String name) {
		StringBuffer sql = new StringBuffer(" 1=1 ");
		JSONArray array = new JSONArray();
		if (null != updateTimeStart && null != updateTimeEnd) {
			sql.append("and updateTime between ? and ?");
			array.add(updateTimeStart);
			array.add(updateTimeEnd);
		}
		if (null != name) {
			sql.append("and name like ?");
			array.add("%" + name + "%");
		}
		return superDao.findByCondition(sql.toString(), array.toArray(), "order by updateTime desc", null, CimEquipmentUpdateMessage.class);
	}

	/**
	 * 获取近三天的cim模型更新消息
	 * @param isAlarm  是否只查询告警消息
	 * @return List<CimEquipmentUpdateMessage> 近三天的cim模型更新消息列表
	 */
	public List<CimEquipmentUpdateMessage> findLast3DaysMessages(boolean isAlarm) {
		Date nowDate = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(nowDate);
		calendar.add(Calendar.DAY_OF_MONTH, -3);
		Date date = calendar.getTime();
		StringBuffer sql = new StringBuffer();
		if(isAlarm) {
			sql.append(" isAlarm =  1 and " );
		}
		JSONArray array = new JSONArray();
		if (null != date) {
			sql.append(" updateTime between ? and ?");
			array.add(date);
			array.add(nowDate);
		}
		List<CimEquipmentUpdateMessage> messages = superDao.findByCondition(sql.toString(), array.toArray(), "order by updateTime desc", null, CimEquipmentUpdateMessage.class);
		if (messages != null && messages.size() > 10) {
			List<CimEquipmentUpdateMessage> subMessages = messages.subList(0, 10);
			return subMessages;
		} else {
			return messages;
		}
	}
}
